package suibian;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class League {
    private List<Team> teams;

    public League() {
        teams = new ArrayList<>();
    }

    public void loadTeamsFromFile(String filename) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] data = line.split("\\s+");
                Team team = new Team(data[0]);
                team.matchesPlayed = Integer.parseInt(data[1]);
                team.wins = Integer.parseInt(data[2]);
                team.draws = Integer.parseInt(data[3]);
                team.losses = Integer.parseInt(data[4]);
                team.goalsScored = Integer.parseInt(data[5]);
                team.goalsAgainst = Integer.parseInt(data[6]);
                team.points = Integer.parseInt(data[7]);
                teams.add(team);
            }
        }
    }

    public void updateMatchResult(String homeTeamName, String awayTeamName, int homeGoals, int awayGoals) {
        for (Team team : teams) {
            if (team.getName().equals(homeTeamName)) {
                team.update(homeGoals, awayGoals);
            } else if (team.getName().equals(awayTeamName)) {
                team.update(awayGoals, homeGoals);
            }
        }
    }

    public void sortTeams() {
        Collections.sort(teams);
    }

    public void displayTeams() {
        System.out.println("队名          比赛场数 胜 平 负 进球 失球 积分");
        for (Team team : teams) {
            System.out.println(team);
        }
    }

    public void saveTeamsToFile(String filename) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
            for (Team team : teams) {
                bw.write(team.toString());
                bw.newLine();
            }
        }
    }
}
